﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Tunneler.Tools;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;

namespace Tunneler {
    class Explosion : IGameObject {
        static string[] textureNames = { "explosion1", "explosion2", "explosion3", "explosion4", "explosion5" };

        static List<Texture2D> textures = new List<Texture2D>();
        static List<Color[]> texturesData = new List<Color[]>();

        Vector2 position;
        float rotation;
        float textureScale = 1f;

        int state;
        bool finnished;

        Cooldown textureChangeCD;

        public Texture2D Texture { get { return textures[state]; } }
        public Color[] TextureData { get { return texturesData[state]; } }
        public Vector2 Origin { get { return new Vector2(textures[state].Width / 2, textures[state].Height / 2); } }

        public Vector2 Position { get { return position; } }
        public float Rotation { get { return rotation; } }

        public float TextureScale { get { return textureScale; } set { textureScale = value; } }

        public Explosion(Vector2 position, float rotation) {
            this.position = position;
            this.rotation = rotation;
        }

        public void Update(GameTime gameTime) {
            if (textureChangeCD == null) {
                textureChangeCD = new Cooldown(gameTime, 20);
                textureChangeCD.Use();
            }

            if (finnished) {
                if (textureChangeCD.IsCool()) {
                    KillSelf();
                }
                return;
            }

            if (textureChangeCD.IsCool()) {
                state++;
                if (state == textures.Count) {
                    state--;
                    finnished = true;
                }
                textureChangeCD.Use();
            }
        }

        public void LoadContent(ContentManager content) {
            foreach (string tName in textureNames) {
                Texture2D t = content.Load<Texture2D>(tName);
                Color[] tData = new Color[t.Width * t.Height];
                t.GetData<Color>(tData);

                textures.Add(t);
                texturesData.Add(tData);
            }
        }

        public void Draw(SpriteBatch spriteBatch) {
            spriteBatch.Draw(Texture, Position, null, Color.White, Rotation, Origin, TextureScale, SpriteEffects.None, 0);
        }

        public void TouchedBy(Terrain terrain) {
            // Nothing happens. Only terrain is affected.
        }

        public void TouchedBy(IGameObject gameObject) {
            // No effect.
        }

        private void KillSelf() {
            World.Instance.DeleteGameObject(this);
        }
    }
}
